package com.deyuanyun.pic.ctrl.controller;

import com.alibaba.fastjson.JSONObject;
import com.deyuanyun.pic.common.tool.StaticParam;
import com.deyuanyun.pic.common.util.MyCollectionUtil;
import com.deyuanyun.pic.common.util.ObjectUtil;
import com.deyuanyun.pic.common.util.StringUtils;
import com.deyuanyun.pic.common.util.ajax.AjaxResponse;
import com.deyuanyun.pic.common.util.poi.ReadExcel;
import com.deyuanyun.pic.common.util.web.DownLoadUtil;
import com.deyuanyun.pic.common.util.web.RequestResponseContext;
import com.deyuanyun.pic.common.validator.imlclass.BeanValidateUtil;
import com.deyuanyun.pic.common.validator.imlclass.VResult;
import com.deyuanyun.pic.ctrl.annotation.DbTable;
import com.deyuanyun.pic.ctrl.controller.dto.ExinspTaskExpandDTO;
import com.deyuanyun.pic.ctrl.excelImport.*;
import com.deyuanyun.pic.ctrl.service.ExternalInspProjectService;
import com.deyuanyun.pic.ctrl.service.ImportService;
import com.deyuanyun.pic.ctrl.util.AcOrDcUtil;
import com.deyuanyun.pic.ctrl.util.AutoImport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 导入控制类
 *
 * @author scalpel.王敏
 * @version [v1.0] 创建时间（2016/9/18）
 * @see // 引用的类
 * Method List:
 * 1.----------------
 * 2.----------------
 * History:
 */
@Controller
@RequestMapping("/corrctrl/dataImport")
public class ImportController {

    Log log = LogFactory.getLog(ImportController.class);
    @Resource
    private ImportService importService;

    @Resource
    private ExternalInspProjectService externalInspProjectService;

    static Map<String,Class> classMap=new HashMap<String, Class>();


    /**
     * 初始化导入类型
     */
    static {
        classMap.put("acMiorRecord",PicCtrlExinspAcMiorRecordExcel.class);
        classMap.put("anodesbed",PicCtrlExinspAnodesbedExcel.class);
        classMap.put("antiSurge",PicCtrlExinspAntiSurgeExcel.class);
        classMap.put("curiedDepth",PicCtrlExinspBuriedDepthExcel.class);
        classMap.put("cipsDcvg",PicCtrlExinspCipsDcvgExcel.class);
        classMap.put("cpjumper",PicCtrlExinspCpjumperExcel.class);
        classMap.put("cppower",PicCtrlExinspCppowerExcel.class);
        classMap.put("cptestStation",PicCtrlExinspCptestStationExcel.class);
        classMap.put("dcMiorRecord",PicCtrlExinspDcMiorRecordExcel.class);
        classMap.put("drainage",PicCtrlExinspDrainageExcel.class);
        classMap.put("insedJoint",PicCtrlExinspInsedJointExcel.class);
        classMap.put("ocgrade",PicCtrlExinspOcgradeExcel.class);

        classMap.put("oclpointDig",PicCtrlExinspOclpointDigExcel.class);
        classMap.put("oclpoint",PicCtrlExinspOclpointExcel.class);
        classMap.put("pcmAcvg",PicCtrlExinspPcmAcvgExcel.class);
        classMap.put("pipeCorsTest",PicCtrlExinspPipeCorsTestExcel.class);

        classMap.put("pipeSpanTest",PicCtrlExinspPipeSpanTestExcel.class);

        classMap.put("reference",PicCtrlExinspReferenceExcel.class);
        classMap.put("saalAnode",PicCtrlExinspSaalAnodeExcel.class);
        classMap.put("soilCorr",PicCtrlExinspSoilCorrExcel.class);
    }


    @RequestMapping("/page.html")
    public String page(Model model)
    {
        String id = AutoImport.getExInspTaskId();
        ExinspTaskExpandDTO exinspTaskExpand = externalInspProjectService.getInfoById(id);
        model.addAttribute("exInspTaskId", id);
        model.addAttribute("exInspTask", exinspTaskExpand);
        return "corrctrl/external/projectManagementInfo";
//        return "corrctrl/import/page";
    }

    /**
     * 腐蚀控制外检数据导入
     * @author       scalpel.王敏
     * @version      创建时间（2016/10/14 9:30）
     * @param type String 导入类型
     * @param file File 导入的excel文件
     * @return
     * @throws
     */
    @ResponseBody
    @RequestMapping("/{type}/import.json")
    public void importData(MultipartFile file,@PathVariable String type, HttpServletResponse response) throws Exception {

        String exInspTaskId = AutoImport.getExInspTaskId();
        if(StringUtils.isEmpty(exInspTaskId))
        {
            response.setStatus(503);
            AjaxResponse.sendText(response,StaticParam.getUploadFileFailResultMessage("参数错误。"));
            return ;
        }
        Class c=classMap.get(type);
        if(c != null)
        {
            InputStream in=file.getInputStream();

            String result=AutoImport.checkHead(in,c);
            if(result.length() > 0)
            {
                response.setStatus(503);
                AjaxResponse.sendText(response, StaticParam.getUploadFileFailResultMessage(result));
                return ;
            }

            in=file.getInputStream();

            DbTable dbTable= (DbTable) c.getAnnotation(DbTable.class);
            List data= ReadExcel.readExcle(c,in,dbTable.startRow(),(dbTable.sumCell()-1)+"");
            data= MyCollectionUtil.removeLastEmpty(data);
            if("oclpoint".equals(type))
            {
                RequestResponseContext.getRequest().setAttribute("oclpoint_sessionId",new ArrayList<String>() );
            }
            VResult b= BeanValidateUtil.vali2(data,""+dbTable.startRow());
            if (b.isRelult()){

                    

                try{
                    //补充绝对距离
                    AutoImport.getPointData(data);
                    //初始化附近测试桩
                    AutoImport.initNagm(data);

                    importService.saveImportData(data,c);
                    AjaxResponse.sendText(response, StaticParam.UPLOAD_FILE_SUCCESS);
                }catch (Exception e)
                {
                    log.error("导入数据失败",e);
                    e.printStackTrace();
                    result="导入失败!"+e.getMessage();
                    response.setStatus(503);
                    AjaxResponse.sendText(response,StaticParam.getUploadFileFailResultMessage(result));
//                    e.printStackTrace();
                }
            }else{
                String[] titleArr= AutoImport.getFiledNames(c);//ReadExcel.getTitle(file,"in/valve_room_t.xls");
                String m=b.getAllString(titleArr);
                response.setStatus(503);
                AjaxResponse.sendText(response,StaticParam.getUploadFileFailResultMessage(m));
            }
        }else{
            response.setStatus(503);
            AjaxResponse.sendText(response,StaticParam.getUploadFileFailResultMessage("没有找到对应的表单。"));
        }



    }


    /**
     * 腐蚀控制散杂流干扰数据导入
     * @author       scalpel.王敏
     * @version      创建时间（2016/10/14 9:30）
     * @param type String 导入类型
     * @param file File 导入的excel文件
     * @return
     * @throws
     */
    @ResponseBody
    @RequestMapping("/{type}/importDisturbeddata.json")
    public void importDisturbeddata(MultipartFile file,@PathVariable String type,HttpServletRequest request, HttpServletResponse response) throws Exception {
        String table = null;
        String recordTable = null;
        if ("ac".equals(type))
        {
            table="PIC_CTRL_EXINSP_AC_MIOR_DATA";
            recordTable="PIC_CTRL_EXINSP_AC_MIOR_RECORD";
        }else if("dc".equals(type)){
            table="PIC_CTRL_EXINSP_DC_MIOR_DATA";
            recordTable="PIC_CTRL_EXINSP_DC_MIOR_RECORD";
        }


        //监控记录编号
        String baseid=request.getParameter("baseid");
        String exInspTaskId=request.getParameter("exInspTaskId");
        if(StringUtils.isEmpty(baseid) || StringUtils.isEmpty(exInspTaskId))
        {
            response.setStatus(503);
            AjaxResponse.sendText(response,StaticParam.getUploadFileFailResultMessage("参数错误。"));
            return;
        }

        //查询监测数据
        String databaseid = importService.queryAcOrDc(type,baseid);
        if(StringUtils.isEmpty(databaseid))
        {
            response.setStatus(503);
            AjaxResponse.sendText(response,StaticParam.getUploadFileFailResultMessage("找不到监测数据。"));
            return;
        }

        try {
                List<InterferenceMonitoringExcel> data= ReadExcel.readExcle(InterferenceMonitoringExcel.class,file.getInputStream(),2,"2");
                data= MyCollectionUtil.removeLastEmpty(data);
                VResult b= BeanValidateUtil.vali2(data,"2");
                if (b.isRelult() ){
                    if(table == null)
                    {
                        response.setStatus(503);
                        AjaxResponse.sendText(response,StaticParam.getUploadFileFailResultMessage("导入类型错误!"));
                        return;
                    }
                    List targerData = new ArrayList();
                    List t = null;
                    for(InterferenceMonitoringExcel ime:data)
                    {
                        t = new ArrayList();
                        t.add(ime.getTestTime());
                        t.add(ime.getAcInterferenceVoltage());
                        targerData.add(t);
                    }


                    HashMap param=new HashMap();

                    if("ac".equals(type))
                    {
                        AcOrDcUtil.acAvg(data,param);
                    }else{
                       String error = AcOrDcUtil.dcAvg(data,param);
                        if(error != null)
                        {
                            response.setStatus(503);
                            AjaxResponse.sendText(response,StaticParam.getUploadFileFailResultMessage(error));
                            return ;
                        }
                    }

                    param.put("id", StringUtils.getRandUUID());
                    param.put("baseid", baseid);
                    param.put("table",table);
                    param.put("recordTable",recordTable);

                    param.put("type",type);
                    param.put("data", JSONObject.toJSONString(targerData));
                    importService.inserMiorData(param);
                    AjaxResponse.sendText(response, StaticParam.UPLOAD_FILE_SUCCESS);

            }else{
                String[] titleArr= new String[]{"测试时间","ac".equals(type)?"交流电压（V）":"管/地电位（mV，vs.CSE）"};//ReadExcel.getTitle(file,"in/valve_room_t.xls");
                String m=b.getAllString(titleArr);
                response.setStatus(503);
                AjaxResponse.sendText(response,StaticParam.getUploadFileFailResultMessage(m));
            }
        }catch (Exception e){
            e.printStackTrace();
            response.setStatus(503);
            AjaxResponse.sendText(response,StaticParam.getUploadFileFailResultMessage("导入失败，请检测导入模板"));
        }



    }



    @ResponseBody
    @RequestMapping("/{type}/downImportTml.json")
    public void downImportTml(@PathVariable String type, HttpServletResponse response) throws Exception {



        Class c=classMap.get(type);
        if(c != null)
        {
            DbTable table = (DbTable) c.getAnnotation(DbTable.class);
            String exceName = table.excelName();
            String suffix = exceName.substring(exceName.lastIndexOf("."));
//            suffix = suffix.substring(0,suffix.length()-1);
            String templateName="excl/ctrl/out/"+type+suffix;
            Workbook workbook= ReadExcel.readExcelTemplate(templateName);
            initExcelDownResponse(response, exceName);
            excelOut(response,workbook);
        }else{
            if("ac".equals(type))
            {
                String exceName="交流流干扰监测数据表";
                String templateName="excl/ctrl/out/acData.xls";
                Workbook workbook= ReadExcel.readExcelTemplate(templateName);
                initExcelDownResponse(response, exceName);
                excelOut(response,workbook);
            }else if("dc".equals(type)){
                String exceName="直流流干扰监测数据表";
                String templateName="excl/ctrl/out/dcData.xls";
                Workbook workbook= ReadExcel.readExcelTemplate(templateName);
                initExcelDownResponse(response, exceName);
                excelOut(response,workbook);
            }else{
                response.setHeader("Content-Disposition","");
                AjaxResponse.sendText(response,"<script>alert('参数错误！');</script>");
            }
        }


    }


    /**
     * 初始化excel的下载
     * @param response
     * @param fileName
     */
    public static void initExcelDownResponse(HttpServletResponse response,String fileName){

        String userAgent = RequestResponseContext.getRequest().getHeader("User-Agent");
        try {
            fileName = DownLoadUtil.encodeDownloadName(fileName, userAgent);
        } catch (Exception e) {
            fileName = "fileName";
        }
//        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet ; charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition","attachment;filename="+ fileName);
    }

    /**
     * 输出excel
     * @param response
     */
    public static void excelOut(HttpServletResponse response,Workbook workbookFinal) {
        if (ObjectUtil.isEmptyAll(workbookFinal)){
            response.setHeader("Content-Disposition","");
            AjaxResponse.sendText(response,"<script>alert('数据为空，不可进行下载操作!');</script>");
            return;
        }
        ServletOutputStream outputStream=null;
        try {
            outputStream = response.getOutputStream();
            workbookFinal.write(outputStream);
            outputStream.flush();
        } catch (IOException e) {

        } finally {
            if (outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {

                }
            }

        }
    }

}
